// pages/index/index.js
const app = getApp();
import request from "../../utils/request.js";
const themeManager = require("../../utils/theme.js");

Page(themeManager.enhancePage({
  data: {
    deviceCount: 0,
    deviceOnlineCount: 0,
    ticketAwaitingCount: 0,
    deviceList: [],
    loading: true,
    latestAnnouncement: {},
    currentTheme: 'dark', // 添加主题状态
  },

  onLoad: function (options) {
    this.loadStatistics();
    this.loadDeviceList();
    this.loadLatestAnnouncement(); // 加载公告数量
  },

  onShow: function () {
    // 页面显示时刷新数据
    this.loadDeviceList();
  },

  // 加载统计数据
  loadStatistics: function () {
    // 模拟数据，实际项目中应该调用API
    request
      .get("/devices/my_devices?status=1")
      .then((res) => {
        if (res) {
          this.setData({
            deviceOnlineCount: res.data.count,
          });
        }
      })
      .catch((err) => {
        console.error("加载设备列表失败:", err);
        this.showError("加载设备列表失败，请稍后重试");
        // this.loadMockData() // 加载模拟数据
      });

    request
      .get("/tickets/my_tickets?status=1")
      .then((res) => {
        if (res) {
          this.setData({
            ticketAwaitingCount: res.data.count,
          });
        }
      })
      .catch((err) => {
        console.error("加载设备列表失败:", err);
        this.showError("加载设备列表失败，请稍后重试");
        // this.loadMockData() // 加载模拟数据
      });
  },

  // 加载设备列表
  loadDeviceList: function () {
    this.setData({ loading: true });
    request
      .get("/devices/my_devices")
      .then((res) => {
        if (res) {
          this.setData({
            deviceList: res.data.items,
            deviceCount: res.data.count,
            loading: false,
          });
        }
      })
      .catch((err) => {
        console.error("加载设备列表失败:", err);
        this.showError("加载设备列表失败，请稍后重试");
        // this.loadMockData() // 加载模拟数据
      });
  },

  // 跳转到设备详情页
  goToDeviceDetail: function (e) {
    const device = e.currentTarget.dataset.device;
    console.log("跳转到设备详情页，设备信息:", device.uuid);
    wx.navigateTo({
      url: `/pages/device/devices?deviceId=${device.uuid}`,
    });
  },

  // 添加设备
  addDevice: function () {
    wx.showActionSheet({
      itemList: [
        "扫描二维码添加（位于设备底部）",
        "手动输入序列号（位于设备底部）",
      ],

      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            wx.scanCode({
              onlyFromCamera: true,
              success: (scanRes) => {
                const uuid = scanRes.result.trim();
                if (uuid) {
                  this.performAddDevice(uuid);
                  return;
                }
              },
              fail: (err) => {
                wx.showToast({
                  title: "扫描失败，请重试",
                  icon: "none",
                });
              },
            });
            break;
          case 1:
            wx.showModal({
              title: "手动输入序列号",
              content: "",
              editable: true,
              placeholderText: "请输入设备底部的序列号",
              success: (modalRes) => {
                if (modalRes.confirm) {
                  const uuid = modalRes.content.trim();
                  if (uuid) {
                    this.performAddDevice(uuid);
                  } else {
                    wx.showToast({
                      title: "序列号不能为空",
                      icon: "none",
                    });
                  }
                }
              },
            });
            break;
          default:
            return; // 用户取消操作
        }
      },
    });
  },

  performAddDevice: function (uuid) {
    console.log("添加设备，序列号:", uuid);
    request
      .post(`/devices/${uuid}/bind`)
      .then((res) => {
        if (res && res.data.status === 0) {
          wx.showToast({
            title: "设备添加成功",
            icon: "success",
          });
          this.refreshDevices(); // 刷新设备列表
        } else {
          console.error("添加设备失败:", res.data);
          this.showError(res.data.message || "设备添加失败，请稍后重试");
        }
      })
      .catch((err) => {
        console.error("添加设备失败:", err);
        this.showError(err.message || "设备添加失败，请稍后重试");
      });
  },

  // 刷新设备列表
  refreshDevices: function () {
    wx.showToast({
      title: "正在刷新...",
      icon: "loading",
      duration: 300,
    });
    this.loadDeviceList();
  },

  // 显示错误信息
  showError: function (message) {
    this.setData({ loading: false });
    wx.showToast({
      title: message,
      icon: "none",
    });
  },

  loadLatestAnnouncement: function () {
    request.get("/announcements").then((res) => {
      this.setData({ latestAnnouncement: res.data.items[0] });
    });
  },

  goToAnnouncementDetail: function () {
    wx.navigateTo({
      url:
        "/pages/announcement/announcement?announcementId=" +
        this.data.latestAnnouncement.uuid,
    });
  },
}));
